package com.cai.demo.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

/**
 * @Title: JWTUtil
 * @Author RuoLi
 * @Package com.cai.demo.util
 * @Date 2023/12/14 22:20
 * @description: JWT工具类
 */
@Slf4j
public class JWTUtil {
    //秘钥
    private static String SECRET = "49191uhghjfhfggfcfg56151655";
    //token有效时间
    private static Long durationInMinutes = 60L;

    //创建token
    //传入userId
    public static String createToken(String data) {
        //设置过期时间
        Date expireDate = new Date(System.currentTimeMillis() + 60 * 1000 * durationInMinutes);
        return Jwts.builder().setHeaderParam("typ", "JWT")
                .setSubject(data)
                .setIssuedAt(new Date())
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();
    }
    //校验JWT
    public static Claims parseToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
    }

    //校验token是否过期
    public static boolean isTokenExpired(String token) {
        Claims claims = parseToken(token);
        return claims.isEmpty();
    }
}
